package com.liliudong.cursormate.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liliudong.cursormate.common.R;
import com.liliudong.cursormate.common.exception.BusinessException;
import com.liliudong.cursormate.entity.SysOrg;
import com.liliudong.cursormate.service.SysOrgService;
import com.liliudong.cursormate.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 系统组织控制器
 *
 * @author liudo
 * @version 1.0
 * @project cursor-mate
 * @date 2023/10/26 20:29:20
 */
@RestController
@RequestMapping("/v1/sys-org")
@RequiredArgsConstructor
public class SysOrgController {

    private final SysOrgService sysOrgService;

    private final SysUserService sysUserService;

    /**
     * 新增
     *
     * @param sysOrg sys组织
     * @return {@link R}<{@link ?}>
     */
    @PostMapping
    @SaCheckPermission("sys:org:add")
    public R<?> create(@RequestBody SysOrg sysOrg) {
        sysOrgService.create(sysOrg);
        return R.success();
    }

    /**
     * 根据ID删除
     *
     * @param id id
     * @return {@link R}<{@link ?}>
     */
    @DeleteMapping("/{id}")
    @SaCheckPermission("sys:org:del")
    public R<?> del(@PathVariable Long id) {
        int count = sysUserService.countByOrgId(id);
        if (count > 0) {
            throw new BusinessException("该组织下存在用户，无法删除");
        }
        sysOrgService.removeById(id);
        return R.success();
    }

    /**
     * 使现代化
     *
     * @param sysOrg sys组织
     * @return {@link R}<{@link ?}>
     */
    @PutMapping
    @SaCheckPermission("sys:org:edit")
    public R<?> update(@RequestBody SysOrg sysOrg) {
        sysOrg.setOrgNo(null);
        sysOrgService.updateById(sysOrg);
        return R.success();
    }

    /**
     * 分页查询
     *
     * @param page     页
     * @param pageSize 页面大小
     * @return {@link R}<{@link Page}<{@link SysOrg}>>
     */
    @GetMapping("/page")
    @SaCheckPermission("sys:org:page")
    public R<Page<SysOrg>> page(@RequestParam(defaultValue = "1") Long page,
                                @RequestParam(defaultValue = "10") Long pageSize) {
        Page<SysOrg> sysOrgPage = sysOrgService.page(Page.of(page, pageSize));
        return R.success(sysOrgPage);
    }

    /**
     * 查询详情
     *
     * @param id id
     * @return {@link R}<{@link ?}>
     */
    @GetMapping("/{id}")
    @SaCheckPermission("sys:org:info")
    public R<?> query(@PathVariable Long id) {
        return R.success(sysOrgService.getById(id));
    }

}
